package com.zhoug.share.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;


import com.zhoug.common.adapters.recycler.BaseRecyclerViewAdapter;
import com.zhoug.common.permission.PermissionManager;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.ThreadUtils;
import com.zhoug.common.utils.ToastUtils;
import com.zhoug.share.R;
import com.zhoug.share.core.ClientType;
import com.zhoug.share.core.ShareClientFactory;
import com.zhoug.share.core.ins.ShareCallback;
import com.zhoug.share.core.ins.ShareClient;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 分享窗口
 *
 * @Author HK-LJJ
 * @Date 2019/12/25
 * @Description
 */
public class ShareDialog extends Dialog {
    private static final String TAG = ">>>ShareDialog";
    private List<ShareBean> shareBeans;
    private String path;//分享的图片路径
    private ShareClient shareClient;
    private View contentView;
    private int width = WindowManager.LayoutParams.MATCH_PARENT;
    private int height = WindowManager.LayoutParams.WRAP_CONTENT;
    private int gravity = Gravity.BOTTOM;
    int windowAnimationResId = -1;
    private Object tag;

    public ShareDialog(@NonNull Context context) {
        super(context,R.style.share_dialog_full);
    }

    public ShareDialog(@NonNull Context context, String path) {
        this(context);
        this.path = path;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//必须设置无标题 否则不会匹配内容
        contentView = LayoutInflater.from(getContext()).inflate( R.layout.share_dialog_share, null);
        setContentView(contentView);
        init();
        _setAttributes();
        if (windowAnimationResId != -1) {
            setWindowAnimations(windowAnimationResId);
        }
    }

    private void initShareBeans() {
        if (shareBeans == null) {
            shareBeans = new ArrayList<>();
            shareBeans.add(new ShareBean("微信", R.drawable.share_icon_share_weixing, ClientType.Wechat));
            shareBeans.add(new ShareBean("QQ", R.drawable.share_icon_share_qq, ClientType.QQ));
            shareBeans.add(new ShareBean("新浪微博", R.drawable.share_icon_share_weibo, ClientType.SinaWeibo));
            shareBeans.add(new ShareBean("保存本地", R.drawable.share_icon_share_local, ClientType.Local));
        }
    }


    protected void init() {
        initShareBeans();
        ShareAdapter shareAdapter = new ShareAdapter();
        shareAdapter.setOnItemClickListener(onItemClickListener);
        shareAdapter.setData(shareBeans);

        RecyclerView shareRecyclerView = findViewById(R.id.recyclerView);
        shareRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
        shareRecyclerView.setAdapter(shareAdapter);

        setDefWindowAnimations();
        setCanceledOnTouchOutside(true);
        setAttributes(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);

    }

    /**
     * item的单击事件
     */
    private BaseRecyclerViewAdapter.OnItemClickListener onItemClickListener = new BaseRecyclerViewAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseRecyclerViewAdapter adapter, View view, int position) {
            cancel();
            ShareBean shareBean = shareBeans.get(position);
            LogUtils.d(TAG, shareBean.getText());
            if (shareClient == null) {
                shareClient = ShareClientFactory.create();
                shareClient.setShareCallback(shareCallback);
            }

            switch (shareBean.getClientType()) {
                case Wechat:
                    shareClient.wechatShare(ShareClient.SHARE_TYPE_IMAGE, path);
                    break;
                case QQ:
                    shareClient.qqShare(ShareClient.SHARE_TYPE_IMAGE, path);
                    break;
                case SinaWeibo:
                    shareClient.sinaWeiboShare(ShareClient.SHARE_TYPE_IMAGE, path);
                    break;
                case Local:
                    new PermissionManager(getContext())
                            .addPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .setCallback((success, denied) -> {
                                if (success) {
                                    LogUtils.d(TAG, "授权成功:");
                                    shareClient.localShare(getContext(),ShareClient.SHARE_TYPE_IMAGE, path);
                                } else {
                                    LogUtils.e(TAG, "权限申请失败:");
                                }
                            })
                            .request();
                    break;
            }
        }
    };

    private ShareCallback shareCallback = new ShareCallback() {
        @Override
        public void onComplete(ClientType clientType, int code) {
            LogUtils.e(TAG, "onComplete:clientType="+clientType+",code="+code);

        }

        @Override
        public void onError(ClientType clientType, int code, String error) {
            LogUtils.e(TAG, "onError:clientType="+clientType+",code="+code+",error="+error);
           ThreadUtils.runMainThread(()-> ToastUtils.toastShort(getContext().getApplicationContext(), error));

        }

        @Override
        public void onCancel(ClientType clientType, int code) {
            LogUtils.e(TAG, "onCancel:clientType="+clientType+",code="+code);

        }
    };


    /**
     * 设置窗口的属性
     *
     * @param width   窗口宽 默认{@link WindowManager.LayoutParams#MATCH_PARENT}
     * @param height  高 例：默认{@link WindowManager.LayoutParams#WRAP_CONTENT}
     * @param gravity {@link Gravity} 默认{@link Gravity#BOTTOM}
     */
    public ShareDialog setAttributes(int width, int height, int gravity) {
        this.width = width;
        this.height = height;
        this.gravity = gravity;
        _setAttributes();
        return this;
    }

    /**
     * 设置窗口的属性
     */
    private void _setAttributes() {
        Window window = this.getWindow();
        if (window == null) {
            return;
        }
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.width = width;
        attributes.height = height;
        attributes.gravity = gravity;
        window.setAttributes(attributes);
    }

    /**
     * 设置动画
     *
     * @param resId 例:com.heking.common.R.style.common_anim_window_popu_down
     */
    public void setWindowAnimations(@StyleRes int resId) {
        windowAnimationResId = resId;
        if (this.getWindow() != null) {
            this.getWindow().setWindowAnimations(resId);
        }
    }

    /**
     * 设置默认动画,从底部弹出
     */
    public void setDefWindowAnimations() {
        setWindowAnimations(com.zhoug.common.R.style.common_anim_window_popu_down);
    }

    public Object getTag() {
        return tag;
    }

    public void setTag(Object tag) {
        this.tag = tag;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}
